package com.jx.service.system;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jx.dao.system.UserRoleDao;
import com.jx.pojo.entity.system.User;
import com.jx.pojo.entity.system.UserRole;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class UserRoleService extends ServiceImpl<UserRoleDao, UserRole> {


    /**
     * 批量新增用户角色关联表
     */
    @Transactional
    public void saveUserRole(User user, List<Integer> roleIds) {

        Integer userId = user.getId();

        // 删除旧数据
        QueryWrapper<UserRole> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        this.remove(wrapper);

        // 保存新数据
        List<UserRole> list = new ArrayList<>();
        for (Integer roleId : roleIds) {
            UserRole userRole = new UserRole();
            userRole.setUserId(userId);
            userRole.setRoleId(roleId);
            list.add(userRole);
        }
         this.saveBatch(list);
    }

    /**
     * 根据用户id获取对应的角色列表
     */
    public List<Integer> getRoleIdsByUserId(Integer userId) {
        QueryWrapper<UserRole> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        List<UserRole> list = this.list(wrapper);
        List<Integer> roleIds = new ArrayList<>();
        for (UserRole userRole : list) {
            roleIds.add(userRole.getRoleId());
        }
        return roleIds;
    }

    /**
     * 根据用户id删除对应的角色
     */
    @Transactional
    public void deleteByUserId(Integer userId) {
        QueryWrapper<UserRole> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId);
        this.remove(wrapper);
    }

}
